//
//  WorkServicesThirdViewController.m
//  ASHT_IOS
//
//  Created by Hui Li on 14-4-11.
//  Copyright (c) 2014年 宋安安. All rights reserved.
//

#import "WorkServicesThirdViewController.h"
#import "WorkServiceEntity.h"
#import "NewsInfoEntity.h"
#import "WorkServicesCell.h"
#import "WebContentViewController.h"
#import "AFAppDotNetAPIClient.h"
#include "MBProgressHUD.h"

@interface WorkServicesThirdViewController ()

@end

@implementation WorkServicesThirdViewController

@synthesize headName;
@synthesize thirdArray;
@synthesize thirdTableView;
@synthesize categoryId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _Adaptation = YES;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _currentPage = 1;
    thirdArray = [NSMutableArray array];
    self.thirdTableView.delegate = self;
    self.thirdTableView.dataSource = self;
    self.headLabel.text = headName;
    if (_refreshHeaderView == nil) {
		
		EGORefreshTableHeaderView *egview =
        [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(
                                                                    0.0f,
                                                                    0.0f-thirdTableView.frame.size.height,
                                                                    thirdTableView.frame.size.width,
                                                                    thirdTableView.frame.size.height)];
        
		egview.delegate = self;
		[thirdTableView addSubview:egview];
        //        [self.view_Content addSubview:egview];
		_refreshHeaderView = egview;
        egview=nil;
		
	}
    [_refreshHeaderView refreshLastUpdatedDate];
    [self initDataSource:0 rowcount:4];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
    {
        if (_Adaptation) {
            self.view_Content.frame=CGRectMake(self.view_Content.frame.origin.x,self.view_Content.frame.origin.y,self.view_Content.frame.size.width,self.view_Content.frame.size.height-20);
            _Adaptation=NO;
        }
        
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 85;
}


-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //去掉分割线
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    return thirdArray.count;
}

//查看表格滚动的位置
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    int curRowCount = 0;
    curRowCount += (indexPath.row + 1);
    //NSLog(@"curRowCount = %d",curRowCount);
    if (curRowCount == _currentPage*4 - 1)
    {
        _currentPage++;
        //NSLog(@"page = %d",_currentPage);
        [self initDataSource:thirdArray.count rowcount:4];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row];
    static NSString *CellIdentifier = @"WorkServicesIdentifier";
    
     WorkServicesThirdCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
	if (cell == nil) {
        NSArray* nibViews =  [[NSBundle mainBundle] loadNibNamed:@"DetailedCell" owner:self options:nil];
        cell = [nibViews objectAtIndex:0];
        nibViews=nil;
        
	}
    if (thirdArray.count>0)
    {
        NewsInfoEntity *entity = [self.thirdArray objectAtIndex:row];
        cell.lab_title.text = entity.title;
        cell.lab_content.text = entity.content;
        [cell imageUrl:entity.imageUrl];
    }
    
    return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSUInteger row = [indexPath row];
    
    WebContentViewController *webVC = [[WebContentViewController alloc] initWithNibName:XIB_Version(@"WebContentViewController") bundle:nil];
    NewsInfoEntity *newEntity = [thirdArray objectAtIndex:row];
    webVC.titleStr = self.headLabel.text;
    webVC.key=newEntity.title;
    webVC.requestStr = [NSString stringWithFormat:SERVER_BASICE_URL@"phone!getArticle.action?articleId=%@",newEntity.articleId];
    [self.app.viewDeckController.navigationController pushViewController:webVC animated:YES];
}

- (void)reloadTableViewDataSource{
    
    //  should be calling your tableviews data source model to reload
    //  put here just for demo
    _reloading = YES;
    
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.thirdTableView];
	
}

#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	//[delegate pullUpdateData];
    //	[self reloadTableViewDataSource];
    
	[thirdArray removeAllObjects];
    _currentPage = 1;
    [self initDataSource:0 rowcount:4];
    //    newsLong=YES;
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}

- (void)egoRefreshTableHeaderDidTriggerToBottom
{
    //    [self initDataSource:thirdArray.count rowcount:6];
}

-(void)initDataSource :(int)startnum rowcount:(int)rowcount
{
    NSString *url = [NSString stringWithFormat:@"/phone!getArticleList.action?categoryId=%@&startnum=%@&rowcount=%i",categoryId,@"0",4];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[AFAppDotNetAPIClient sharedClient] postPath:url parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
        NSDictionary *dic_result=[NSDictionary dictionaryWithDictionary:JSON];
        NSArray *arr_success=[dic_result objectForKey:@"context"];
        
        for (NSDictionary * item in arr_success) {
            NewsInfoEntity *entity = [[NewsInfoEntity alloc] init];
            
            entity.articleId = [item objectForKey:@"articleId"];
            entity.title = [item objectForKey:@"title"];
            entity.imageUrl = [item objectForKey:@"imageUrl"];
            entity.content = [item objectForKey:@"content"];
            [thirdArray addObject:entity];
            entity = nil;
        }
        [thirdTableView reloadData];
       [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        NSString *message=[self ErrorMessageHandling:error];
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                      message:message
                                                     delegate:nil
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
        [alert show];
        alert=nil;

        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
    
}

@end
